//
//  USTodayViewController.m
//  us
//
//  Created by karry on 2025/6/22.
//

#import "USTodayViewController.h"
#import "USTodayMemoryDayCell.h"
#import "USTodayMomentCell.h"
#import "USTodayTarotCell.h"
#import <MJRefresh/MJRefresh.h>
#import "USMomentsModel.h"
#import "USMemorialDayModel.h"
#import "USMomentsDetailController.h"
#import "USMemorialDayDetailVC.h"
#import "USDateAlertView.h"
#import "USTarotModel.h"
#import "USTarotCardDetailController.h"
#import "USTodayTarotController.h"
@interface USTodayViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) USTarotModel *tarotModel;
@property (nonatomic, strong) NSMutableArray <USMemorialDayModel *>*dayList;
@property (nonatomic, strong) NSMutableArray <USMomentsModel *>*momentList;
 
@property (nonatomic, strong) NSDate *date;

@end

@implementation USTodayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     
    self.date = [NSDate date];

    [self setupView];
    [self setupRefresh];
    
    [self.us_tableView.mj_header beginRefreshing];
}

- (void)setupView{
 
    NSString *dayStr = [self.date jk_stringWithFormat:@"M月d日"];
    UILabel *titleLab = [UILabel new];
    titleLab.text = dayStr;
    titleLab.font = [UIFont systemFontOfSize:24 weight:UIFontWeightSemibold];
    [titleLab sizeToFit];
    self.titleLab = titleLab;
    [self.view addSubview:titleLab];
    [titleLab mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.height.mas_equalTo(40);
    }];
    
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"down_arrow"]];
    [titleLab addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLab.mas_right).offset(7);
        make.centerY.mas_equalTo(titleLab);
    }];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] init];
    [titleLab addGestureRecognizer:tapGesture];
    titleLab.userInteractionEnabled = YES;
    @weakify(self)
    [[tapGesture.rac_gestureSignal takeUntil:self.rac_willDeallocSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        @strongify(self);
        USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:self.date andSubTitle:@"选择日期" limitToNow:YES];
        [alert showInView:UIViewController.topViewController.view];
        @weakify(self)
        alert.didChooseBlock = ^(NSDate * _Nonnull date) {
            @strongify(self)
              
            self.date = date;
            NSString *dayStr = [self.date jk_stringWithFormat:@"M月d日"];
            self.titleLab.text = dayStr;
            [self requestNet];
         };
    }];
    
    [self.us_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight);
        make.top.equalTo(titleLab.mas_bottom).offset(10);
        make.bottom.mas_offset(0);
    }];
    
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    self.us_tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.us_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.us_tableView.backgroundColor = UIColor.clearColor;
 
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTodayMemoryDayCell" bundle:nil] forCellReuseIdentifier:@"USTodayMemoryDayCellId"];
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTodayMomentCell" bundle:nil] forCellReuseIdentifier:@"USTodayMomentCellId"];
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USTodayTarotCell" bundle:nil] forCellReuseIdentifier:@"USTodayTarotCellId"];

 
}
- (void)setupRefresh {
    @weakify(self)
    self.us_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self requestNet];
    }];
 
}
#pragma mark - Net
- (void)requestNet {
    [self startLoading];
 
    if (USUser.user.relStatus == 0) {
        [self.us_tableView reloadData];
        [self loadingSuccess];
        
        [self.us_tableView.mj_header endRefreshing];
        return;
    }
    
    NSString *dayStr = [self.date jk_stringWithFormat:@"yyyy-MM-dd"];
    NSDictionary *params = @{@"createTime":dayStr};
    RACSignal *anniversarySignal = [self fetchAnniversaryWithParams:params];
    RACSignal *tarotSignal = [self fetchTarotWithParams:params];
    RACSignal *momentsSignal = [self fetchMomentsWithParams:params];

    NSMutableArray *signList = [NSMutableArray arrayWithArray:@[anniversarySignal,tarotSignal,momentsSignal]];
 
    @weakify(self);
    [[RACSignal zip:signList]
     subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
  
 
        [self.us_tableView reloadData];
        [self loadingSuccess];
        
        [self.us_tableView.mj_header endRefreshing];
    } error:^(NSError *error) {
        @strongify(self);
        [self loadingFailed];
        [self.us_tableView.mj_header endRefreshing];

    }];
}

- (RACSignal *)fetchAnniversaryWithParams:(NSDictionary *)params {
 
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[EMNetWork shareManager] em_post:API_AnniversaryList
                                   params:nil
                                      hud:nil
                               showError:YES
                                  success:^(EMApiModel *api) {
            if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
                [subscriber sendError:[NSError errorWithDomain:@"接口失败" code:-1 userInfo:nil]];
                return;
            }
            USMemorialDaySuperModel *superModel = [USMemorialDaySuperModel mj_objectWithKeyValues:api.data];
            [self.dayList removeAllObjects];
            
            NSMutableArray *dayArr = [NSMutableArray array];
            
            [dayArr addObjectsFromArray:superModel.noRepeatYearlylist];
            [dayArr addObjectsFromArray:superModel.repeatYearlylist];

            for (USMemorialDayModel *model in dayArr) {
                NSLog(@"countdown --- %li",[model countdownToDate:self.date]);
                if ([model countdownToDate:self.date] == 0) {
                    [self.dayList addObject:model];
                }
            }
            
            [subscriber sendNext:superModel];
            [subscriber sendCompleted];
        } fail:^{
            [subscriber sendError:[NSError errorWithDomain:@"网络错误" code:-1 userInfo:nil]];
 
        }];
        
        return nil;
    }];
}
- (RACSignal *)fetchMomentsWithParams:(NSDictionary *)params {
 
    NSMutableDictionary *p = [NSMutableDictionary dictionaryWithDictionary:params];
    [p setObject:@"1" forKey:@"type"];
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[EMNetWork shareManager] em_post:MoodDiaryList
                                   params:p
                                      hud:nil
                               showError:YES
                                  success:^(EMApiModel *api) {
            if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
                [subscriber sendError:[NSError errorWithDomain:@"接口失败" code:-1 userInfo:nil]];
                return;
            }
            NSArray *records = [USMomentsModel mj_objectArrayWithKeyValuesArray:api.data[@"totalMoodDiaryList"]];
            [self.momentList removeAllObjects];
            [self.momentList addObjectsFromArray:records];
                 
            [subscriber sendNext:records];
            [subscriber sendCompleted];
           
        } fail:^{
            [subscriber sendError:[NSError errorWithDomain:@"网络错误" code:-1 userInfo:nil]];
 
        }];
        
        return nil;
    }];
}
- (RACSignal *)fetchTarotWithParams:(NSDictionary *)params {
  
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[EMNetWork shareManager] em_post:TarotTotal
                                   params:params
                                      hud:nil
                               showError:YES
                                  success:^(EMApiModel *api) {
            if (!api.success || ![api.data isKindOfClass:[NSDictionary class]]) {
                [subscriber sendError:[NSError errorWithDomain:@"接口失败" code:-1 userInfo:nil]];
                return;
            }
            USTarotModel *model = [USTarotModel mj_objectWithKeyValues:api.data[@"totalTarot"]];
            self.tarotModel = model;
            
            [subscriber sendNext:model];
            
            [subscriber sendCompleted];
            
        } fail:^{
            [subscriber sendError:[NSError errorWithDomain:@"网络错误" code:-1 userInfo:nil]];
 
        }];
        
        return nil;
    }];
}
 
 
 
- (NSMutableArray <USMemorialDayModel *>*)dayList {
    if (_dayList == nil) {
        _dayList = [NSMutableArray array];
    }
    return _dayList;
}
 

- (NSMutableArray <USMomentsModel *>*)momentList {
  if (_momentList == nil) {
      _momentList = [NSMutableArray array];
  }
  return _momentList;
}

#pragma mark - UITableViewDelegate
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.dayList.count;
    }else if (section == 1) {
        return self.tarotModel.tarotDetailList.count;
    }else {
        return self.momentList.count;
    }
 }

 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        USTodayMemoryDayCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTodayMemoryDayCellId"];

        cell.dayModel = self.dayList[indexPath.row];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 1) {
        USTodayTarotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTodayTarotCellId"];
      
        cell.tarotDetailModel = self.tarotModel.tarotDetailList[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else  {
        USTodayMomentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTodayMomentCellId"];
      
        cell.momentsModel = self.momentList[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
  
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        USMemorialDayDetailVC *vc = [[USMemorialDayDetailVC alloc]init];
        vc.dayModel = self.dayList[indexPath.item];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 1) {
        
        if (self.tarotModel && self.tarotModel.myStatus == 0) {
            //我没完成
            USTodayTarotController *vc = [USTodayTarotController new];
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }
        USTarotCardDetailController *vc = [[USTarotCardDetailController alloc]init];
        if (self.tarotModel) {
            vc.tarotModel = self.tarotModel;
            
            for (USTarotDetailModel *detailModel in self.tarotModel.tarotDetailList) {
                USTarotCard *card = [USTarotCard new];
                
                card = [[USTarotCard alloc] init];
                card.name = detailModel.tarotTitle;
                card.orientation = detailModel.orientation;
                card.imageName = detailModel.tarotTitle;
                card.answer = detailModel.tarotContent;
                card.date = [NSDate dateWithTimeIntervalSince1970:detailModel.gmtCreate];
                if ([detailModel.userId isEqualToString:USUser.user.userId]) {
                    vc.activeCard = card;
                }else {
                    vc.relActiveCard = card;
                }
            }
           
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else  {
        USMomentsDetailController *vc = [[USMomentsDetailController alloc]init];
        vc.momentModel = self.momentList[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }
  
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return self.dayList.count > 0 ? 30 : 0;
    }else if (section == 1) {
        return self.tarotModel.tarotDetailList.count > 0 ? 30 : 0;
    }else {
        return self.momentList.count > 0 ? 30 : 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.backgroundColor = UIColor.mi_2_color;
    UILabel *lab = [[UILabel alloc]init];
    lab.textColor = UIColor.labelColor;
    lab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
    }];
    if (section == 0) {
        lab.text = @"纪念日";
    }else if (section == 1){
        lab.text = @"塔罗牌";
    }else {
        lab.text = @"日记";
    }
    return view;
}

#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate


- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    
    if (self.dataState == EmptyDataStateLoading) {
        UIView *contentView = [UIView new];
        contentView.frame = CGRectMake(0, 0, self.view.jk_width, 200);
        
        NSString *gifPath = [[NSBundle mainBundle] pathForResource:@"load_page" ofType:@"gif"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = CGRectMake(0, 0, 200, 200);
        [imageView sd_setImageWithURL:[NSURL fileURLWithPath:gifPath]];
        
        [contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(200);
            make.center.mas_equalTo(contentView);
        }];
        
        return contentView;
    }
    
    USEmptyView *emptyView = [[USEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.jk_width, 0)];
    emptyView.image = [UIImage imageNamed:@"today_Empty"];
    emptyView.title = @"今天没有互动哦～";
    emptyView.btn.hidden = YES;
    return emptyView;
    
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    
    
    return YES; // 允许点击
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    
    
    return YES; // 避免 scrollView 吃掉 touch 事件
}


@end
